﻿using Studio77.GuessTheWords2.Entities;
using Studio77.GuessTheWords2.Util;
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Studio77.GuessTheWords2.Core
{
    public class StageManager
    {
        public static StageManager Instance = new StageManager();

        private StageManager()
        {
        }

        private static String LAST_STAGE_KEY = "lastStageKey";
        private static String LAST_GAME_CLASS_KEY = "lastGameClassKey";
        private static String LAMP_COUNT_KEY = "iyoye9820937980132";
        private static String CLASS_UNLOCK_KEY = "liulkjsdvbnakuylertngs";
        //private static String IS_AUDIO_OPEN_KEY = "IsAudioOpenKey";
        private const string IS_PLAY_SOUND_KEY = "isPlaySoundKey";
        private const string NEW_USER_TASK_KEY = "newUserTaskKey";
        private const string MARKET_COMMENT = "marketComment";
        private const string LAUNCH_COUNT = "launchCount";

        // 每个关卡的Key前缀
        private static String STATE_DATA_ONE_KEYPRE = "OneStage";

        private const string LAST_FULLSCREEN_DATE_KEY = "LAST_FULLSCREEN_DATE";

        public bool TurnMoka = true;

        public int CurrentStage { get; set; }
        public int CurrentClass { get; set; }

        private string lastFullScreenDate = "XXXXXX";
        /// <summary>
        /// 上一次显示全屏广告的日期
        /// </summary>
        public string LastFullScreenDate
        {
            get
            {
                return lastFullScreenDate;
            }
            set
            {
                lastFullScreenDate = value;
                IsolatedStorageSettings.ApplicationSettings[LAST_FULLSCREEN_DATE_KEY] = lastFullScreenDate;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private bool isDoNewUserTask = false;
        public bool IsDoNewUserTask
        {
            get
            {
                return isDoNewUserTask;
            }
            set
            {
                isDoNewUserTask = value;
                IsolatedStorageSettings.ApplicationSettings[NEW_USER_TASK_KEY] = isDoNewUserTask;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private bool isPlaySound = true;

        /// <summary>
        /// 是否播放音效
        /// </summary>
        public bool IsPlaySound
        {
            get
            {
                return isPlaySound;
            }
            set
            {
                isPlaySound = value;
                IsolatedStorageSettings.ApplicationSettings[IS_PLAY_SOUND_KEY] = isPlaySound;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int lastClass;
        public int LastClass
        {
            get
            {
                return lastClass;
            }
            set
            {
                lastClass = value;
                IsolatedStorageSettings.ApplicationSettings[LAST_GAME_CLASS_KEY] = lastClass;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int lastStage;
        public int LastStage
        {
            get
            {
                return lastStage;
            }
            set
            {
                lastStage = value;
                IsolatedStorageSettings.ApplicationSettings[LAST_STAGE_KEY] = lastStage;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int lampCount = 0;
        public int LampCount
        {
            get
            {
                return lampCount;
            }
            set
            {
                lampCount = value;
                IsolatedStorageSettings.ApplicationSettings[LAMP_COUNT_KEY] = lampCount;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private bool isCommented = false;
        public bool IsCommented
        {
            get
            {
                return isCommented;
            }
            set
            {
                isCommented = value;
                IsolatedStorageSettings.ApplicationSettings[MARKET_COMMENT] = isCommented;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int launchCount = 1;
        public int LaunchCount
        {
            get
            {
                return launchCount;
            }
            set
            {
                launchCount = value;
                IsolatedStorageSettings.ApplicationSettings[LAUNCH_COUNT] = launchCount;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        public Dictionary<string, StageData> StageDatas;
        public Dictionary<string, MapInfo> MapInfos;

        /// <summary>
        /// 载入所有关卡
        /// </summary>
        public void InitAllStages()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains(IS_PLAY_SOUND_KEY) && IsolatedStorageSettings.ApplicationSettings[IS_PLAY_SOUND_KEY] != null)
            {
                isPlaySound = (bool)IsolatedStorageSettings.ApplicationSettings[IS_PLAY_SOUND_KEY];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAST_GAME_CLASS_KEY))
            {
                lastClass = (int)IsolatedStorageSettings.ApplicationSettings[LAST_GAME_CLASS_KEY];
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAST_STAGE_KEY))
            {
                lastStage = (int)IsolatedStorageSettings.ApplicationSettings[LAST_STAGE_KEY];
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAMP_COUNT_KEY))
            {
                lampCount = (int)IsolatedStorageSettings.ApplicationSettings[LAMP_COUNT_KEY];
            }
            else
            {
                LampCount = 6;
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAUNCH_COUNT))
            {
                launchCount = (int)IsolatedStorageSettings.ApplicationSettings[LAUNCH_COUNT];
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(MARKET_COMMENT))
            {
                isCommented = (bool)IsolatedStorageSettings.ApplicationSettings[MARKET_COMMENT];
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(NEW_USER_TASK_KEY))
            {
                isDoNewUserTask = (bool)IsolatedStorageSettings.ApplicationSettings[NEW_USER_TASK_KEY];
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAST_FULLSCREEN_DATE_KEY))
            {
                lastFullScreenDate = (string)IsolatedStorageSettings.ApplicationSettings[LAST_FULLSCREEN_DATE_KEY];
            }

            //读取关卡信息及游戏记录信息
            MapInfos = new Dictionary<string, MapInfo>();

            StageDatas = new Dictionary<string, StageData>();

            if (!IsolatedStorageSettings.ApplicationSettings.Contains(STATE_DATA_ONE_KEYPRE + "1_1"))
            {
                // 初始化关卡,解锁第一章的50个关卡
                IsolatedStorageSettings.ApplicationSettings[CLASS_UNLOCK_KEY + 1] = true;

                int classInditify = 1;
                for (int i = 1; i <= GameStatics.StageCount; i++)
                {
                    String key = classInditify + "_" + i;
                    StageData sd = new StageData();
                    int mapAllCount = WordMapLoader.LoadMapWordCount(key);
                    sd.AllWordCount = mapAllCount;
                    StageDatas.Add(key, sd);
                }
                SaveAllStages();
            }
            else
            {
                for (int classIndex = 1; classIndex <= GameStatics.CurrentOpenedClass; classIndex++)
                {
                    // 检查是否解锁
                    // 初始化关卡,解锁第一章的50个关卡
                    bool isClassUnlocked = false;
                    if (IsolatedStorageSettings.ApplicationSettings.Contains(CLASS_UNLOCK_KEY + classIndex))
                    {
                        isClassUnlocked = (bool)IsolatedStorageSettings.ApplicationSettings[CLASS_UNLOCK_KEY + classIndex];
                    };

                    if (isClassUnlocked)
                    {
                        for (int i = 1; i <= GameStatics.StageCount; i++)
                        {
                            String key = classIndex + "_" + i;
                            if (IsolatedStorageSettings.ApplicationSettings.Contains(STATE_DATA_ONE_KEYPRE + key)
                                && IsolatedStorageSettings.ApplicationSettings[STATE_DATA_ONE_KEYPRE + key] is StageData)
                            {
                                StageData stageData = IsolatedStorageSettings.ApplicationSettings[STATE_DATA_ONE_KEYPRE + key] as StageData;
                                if (stageData.AllWordCount == 0)
                                {
                                    int mapAllCount = WordMapLoader.LoadMapWordCount(key);
                                    stageData.AllWordCount = mapAllCount;
                                }
                                StageDatas.Add(key, stageData);
                            }
                            else
                            {
                                // 如果没有数据，使用一个新数据代替
                                StageData stageData = new StageData();
                                int mapAllCount = WordMapLoader.LoadMapWordCount(key);
                                stageData.AllWordCount = mapAllCount;
                                StageDatas.Add(key, stageData);
                            }
                        }
                    }
                }
            }

        }

        private void SaveAllStages()
        {

            foreach (var key in StageDatas.Keys)
            {
                IsolatedStorageSettings.ApplicationSettings[STATE_DATA_ONE_KEYPRE + key] = StageDatas[key];
            }
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        public void SaveCurrentStageData(String key)
        {

            IsolatedStorageSettings.ApplicationSettings[STATE_DATA_ONE_KEYPRE + key] = StageDatas[key];
            IsolatedStorageSettings.ApplicationSettings.Save();

        }


        /// <summary>
        /// 获取当前关卡完成情况
        /// </summary>
        /// <returns></returns>
        public StageData GetCurrentStageData()
        {
            string key = lastClass + "_" + lastStage;
            if (StageDatas.ContainsKey(key))
            {
                return StageDatas[key];
            }
            else
            {
                return new StageData()
                {
                    AllWordCount = WordMapLoader.LoadMapWordCount(key)
                };
            }
        }


        public void ClearCurrentStage()
        {
            String key = lastClass + "_" + lastStage;
            int wordsCount = StageDatas[key].AllWordCount;
            StageData sd = new StageData();
            sd.AllWordCount = wordsCount;
            StageDatas[key] = sd;

        }

        /// <summary>
        /// 解锁章节
        /// </summary>
        /// <param name="classIndex"></param>
        public void UnlockClassStatus(int classIndex)
        {
            IsolatedStorageSettings.ApplicationSettings[CLASS_UNLOCK_KEY + classIndex] = true;
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        /// <summary>
        /// 获取章节状态 1-正常 2-锁定 3-不可用
        /// </summary>
        /// <param name="classIndex"></param>
        /// <returns></returns>
        public int GetClassStatus(int classIndex)
        {
            if (classIndex <= GameStatics.CurrentOpenedClass)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains(CLASS_UNLOCK_KEY + classIndex))
                {
                    return 1;
                }
                else
                {
                    return 2;
                }
            }
            else
            {
                return 3;
            }
        }

        public void UnlockClassAllStage(int classIndex)
        {
            bool isClassUnlocked = false;
            if (IsolatedStorageSettings.ApplicationSettings.Contains(CLASS_UNLOCK_KEY + classIndex))
            {
                isClassUnlocked = true;
            }

            if (isClassUnlocked)
            {
                for (int i = 1; i <= GameStatics.StageCount; i++)
                {
                    String key = classIndex + "_" + i;
                    if (!IsolatedStorageSettings.ApplicationSettings.Contains(STATE_DATA_ONE_KEYPRE + key))
                    {
                        StageData stageData = new StageData();
                        int mapAllCount = WordMapLoader.LoadMapWordCount(key);
                        stageData.AllWordCount = mapAllCount;
                        StageDatas[key] = stageData;
                    }
                }
                SaveAllStages();
            }
        }

        internal void SaveCurrentStage()
        {
            string key = GetCurrentStageKey();
            IsolatedStorageSettings.ApplicationSettings[STATE_DATA_ONE_KEYPRE + key] = StageDatas[key];
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        internal string GetCurrentStageKey()
        {
            String key = lastClass + "_" + lastStage;
            return key;
        }

        internal void ClearCurrentStageDate()
        {
            int count = StageDatas[GetCurrentStageKey()].AllWordCount;
            StageDatas[GetCurrentStageKey()] = new StageData() { AllWordCount = count };
        }

        /// <summary>
        /// 判断章节解锁
        /// </summary>
        internal int JudgeClassUnlock()
        {
            int unlockIndex = 0;
            for (int classIndex = 2; classIndex <= GameStatics.CurrentOpenedClass; classIndex++)
            {
                if (!IsolatedStorageSettings.ApplicationSettings.Contains(CLASS_UNLOCK_KEY + classIndex))
                {
                    int lastClassIndex = (classIndex - 1);
                    //判断前一个章节完成的状态，130个星以上解锁下一个章节
                    int totalStar = 0;
                    for (int stageIndex = 1; stageIndex <= GameStatics.StageCount; stageIndex++)
                    {
                        String key = lastClassIndex + "_" + stageIndex;
                        if (StageManager.Instance.StageDatas.ContainsKey(key))
                        {
                            StageData sd = StageManager.Instance.StageDatas[key];
                            if (sd.AllWordCount > 0)
                            {
                                totalStar += Misc.GetStar(sd.ComplateCount
                                        / (float)sd.AllWordCount);
                            }
                        }
                    }
                    if (totalStar >= 120)
                    {
                        IsolatedStorageSettings.ApplicationSettings[CLASS_UNLOCK_KEY + classIndex] = true;

                        //增加关卡信息
                        for (int i = 1; i <= GameStatics.StageCount; i++)
                        {
                            String key = classIndex + "_" + i;
                            if (!StageDatas.ContainsKey(key))
                            {
                                StageData sd = new StageData();
                                int mapAllCount = WordMapLoader.LoadMapWordCount(key);
                                sd.AllWordCount = mapAllCount;
                                StageDatas[key] = sd;
                            }
                        }
                        SaveAllStages();

                        unlockIndex = classIndex;
                    }
                    break;
                }
            }
            return unlockIndex;
        }
    }
}
